package com.rainbow.support.mybatis.common;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.rainbow.common.core.error.GlobalException;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 不含缓存的Service实现
 * 重写的目的主要是为了后续扩展缓存
 * @param <M> Mapper
 * @param <T> 实体
 * @author 傅为地
 */
public class CommonServiceImpl<M extends CommonMapper<T>, T> extends ServiceImpl<M, T> implements CommonService<T> {

    /**
     * 默认批次提交数量
     */
    private static final int DEFAULT_BATCH_SIZE = 1000;

    public CommonMapper<T> getSuperMapper() {
        if (ObjectUtils.isNotEmpty(baseMapper)) {
            return baseMapper;
        }
        throw new GlobalException("Mapper转换异常");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertBatch(List<T> list) {
        if (CollectionUtils.isEmpty(list)) {
            return false;
        }
        if (list.size() <= DEFAULT_BATCH_SIZE) {
            return getSuperMapper().insertBatchSomeColumn(list)>0;
        }
        int size = list.size();
        int i = 1;
        List<T> recordList = Lists.newArrayList();
        for (T element : list) {
            recordList.add(element);
            if ((i % DEFAULT_BATCH_SIZE == 0) || i == size) {
                getSuperMapper().insertBatchSomeColumn(recordList);
                recordList.clear();
            }
            i++;
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateBatch(List<T> list) {
        if (CollectionUtils.isEmpty(list)) {
            return false;
        }
        if (list.size() <= DEFAULT_BATCH_SIZE) {
            return getSuperMapper().updateBatchSomeColumnById(list)> 0;
        }
        int size = list.size();
        int i = 1;
        List<T> recordList = Lists.newArrayList();
        for (T element : list) {
            recordList.add(element);
            if ((i % DEFAULT_BATCH_SIZE == 0) || i == size) {
                getSuperMapper().updateBatchSomeColumnById(recordList);
                recordList.clear();
            }
            i++;
        }
        return true;
    }
}
